//
//  VWPlayerLongPressControlLayer.swift
//  VideoPlayer_Example
//
//  Created by JY_NEW on 2021/10/15.
//  Copyright © 2021 CocoaPods. All rights reserved.
//

import ijkPlayerManager
import UIKit
import UICreate

/// 长按快进控制
class VWPlayerLongPressControlLayer: VWPlayerBaseLayer, CAAnimationDelegate {
    
    override var category: VideoPlayerLayerCategory {
        return .control
    }
    
    override var isDeactiveForTapBlank: Bool {
        return false
    }
    
    /// 长按速率
    let targetRate: Float = 2
    /// 原型速率
    var startRate: Float = 0
    
    override func loadManager(_ manager: VideoPlayerLayerManagerType) {
        manager.observer.longPress.addTarget( self, action: #selector(self.onLongPress(_:)))
    }
    override func unloadManager(_ manager: VideoPlayerLayerManagerType) {
        manager.observer.longPress.removeTarget(self)
    }
    override func loadContainerView(_ containerView: UIView) {
        containerView.add(self.contentView, layout: .top(47), .centerX)
    }
    
    @objc func onLongPress(_ gr: UILongPressGestureRecognizer) {
        if !self.isAllowControl { return }
        switch gr.state {
        case .began:
            if let player = self.playerManager, player.status.isPlayingSmoothly, player.rate < self.targetRate {
                self.active()
            }
        case .ended, .cancelled, .failed:
            if self.status.isActived {
                self.deactive()
            }
        default: break
        }
    }
    
    override func show(completion: @escaping () -> Void) {
        self.start()
        self.aniamteShow(for: self.contentView, completion: completion)
        self.currentAnimateTag = 1
        self.contentView.viewWithTag(1)?.layer.add(self.createAnimation(), forKey: "nil")
    }
    override func hide(completion: @escaping () -> Void) {
        self.stop()
        self.aniamteHide(for: self.contentView, completion: completion)
        self.contentView.viewWithTag(self.currentAnimateTag)?.layer.removeAllAnimations()
    }
    func start() {
        if let player = self.playerManager {
            self.startRate = player.rate
            player.rate = self.targetRate
        }
    }
    func stop() {
        self.playerManager?.rate = self.startRate
    }
    
    // MARK: 界面控件
    
    lazy var contentView: UIView = {
        let view = UIView(.height(32), .corner(16), .bg(.init(white: 0, alpha: 0.51)))
        
        let image1 = UIImageView(.image(UIImage(named: "vw_videoFastForward_icon1")?.byTint(.init(rgb: 0xb6b6b6))), .tag(1))
        let image2 = UIImageView(.image(UIImage(named: "vw_videoFastForward_icon1")?.byTint(.init(rgb: 0xC3C3C3))), .tag(2))
        let image3 = UIImageView(.image(UIImage(named: "vw_videoFastForward_icon1")?.byTint(.init(rgb: 0xFFFFFF))), .tag(3))
    

        view.add {
            image1.layout(.left(15), .centerY)
            image2.layout(.rightLeft(3.5), .centerY)
            image3.layout(.rightLeft(3.5), .centerY)
            UILabel(.text("\(Int(self.targetRate)).0X"), .color(.systemBlue), .font(.pingfang(medium: 14))).layout(.rightLeft(3.5), .centerY)
            UILabel(.text("快进中"), .color(.white), .font(.pingfang(medium: 14))).layout(.rightLeft(4.5), .centerY)
                .layout(for: .parent, .right(15))
        }
        
        return view
    }()
    
    var currentAnimateTag = 1
    func createAnimation() -> CABasicAnimation {
        let animate = CABasicAnimation(keyPath: "opacity")
        animate.fromValue = 1
        animate.toValue = 0
        animate.duration = 0.18
        animate.delegate = self
        animate.autoreverses = true
        animate.isRemovedOnCompletion = true
        return animate
    }
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        if flag && self.status.isShowed {
            self.currentAnimateTag += 1
            if self.currentAnimateTag > 3 {
                self.currentAnimateTag = 1
            }
            self.contentView.viewWithTag(self.currentAnimateTag)?.layer.add(self.createAnimation(), forKey: nil)
        }
    }
}
